package ru.stepanovdn.trading.loader

import jakarta.persistence.Persistence
import jakarta.persistence.TypedQuery
import ru.stepanovdn.trading.loader.entity.Candle
import java.time.LocalDate
import java.time.ZoneId

fun main() {
    Class.forName("org.postgresql.Driver");

    val entityManagerFactory = Persistence.createEntityManagerFactory("default")
    val em = entityManagerFactory.createEntityManager()
    em.transaction.begin()
    val query: TypedQuery<Int> = em.createQuery("select max(s.id) from Candle s", Int::class.java)
    val maxIds: List<Int> = query.resultList
    em.transaction.commit()
    print(maxIds[0])

    val timelineStartDate = LocalDate.of(2020, 1, 1)
    var timeline = timelineStartDate.atStartOfDay(ZoneId.of("UTC")).toInstant()

    for (i in 0 .. maxIds[0]) {
        em.transaction.begin()
        val candle = em.find(Candle::class.java, i)
        if (candle != null) {
            val currentTimeline = candle.timeline
            if ("NVTK" != candle.ticker) {
                continue
            }
            timeline = timeline.plusNanos(3600000000000)

            candle.timeline = timeline.atZone(ZoneId.of("UTC")).toLocalDateTime()
            print("id "+ candle.id + "; old "+currentTimeline+"; new "+timeline+"\n")
        }

        em.transaction.commit()
    }

    em.close()
    entityManagerFactory.close()
}